﻿@{
    Layout = "";
}
<style>
    .my-drop-zone {
        border: dotted 3px lightgray;
    }

    .nv-file-over {
        border: dotted 3px red;
    }
    /* Default class applied to drop zones on over */
    .another-file-over-class {
        border: dotted 3px green;
    }

    html, body {
        height: 100%;
    }

    canvas {
        background-color: #f3f3f3;
        -webkit-box-shadow: 3px 3px 3px 0 #e3e3e3;
        -moz-box-shadow: 3px 3px 3px 0 #e3e3e3;
        box-shadow: 3px 3px 3px 0 #e3e3e3;
        border: 1px solid #c3c3c3;
        height: 100px;
        margin: 6px 0 0 6px;
    }

    .ngdialog.ngdialog-theme-plain .ngdialog-content {
        width: 55% !important;
    }

    .form-horizontal .form-group {
        margin-left: 0;
        margin-right: 0;
    }

    .note-image-input {
        margin-bottom: 15px;
    }
</style>
<link href="~/Content/plugins/umeditor/themes/default/css/umeditor.css" rel="stylesheet" />
<script src="~/Content/plugins/umeditor/umeditor.config.js"></script>
<script src="~/Content/plugins/umeditor/umeditor.min.js"></script>
<script src="~/Content/plugins/umeditor/lang/zh-cn/zh-cn.js"></script>
<div ng-controller="ExchangeEditController">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                <form name="formValidate" ng-submit="submitForm()" novalidate="" class="form-validate form-horizontal">
                    <!-- START 基本信息panel-->
                    <div class="panel panel-default" ng-class="{ 'whirl standard': isLoading}">
                        <div class="panel-body">
                            <fieldset class="b0">
                                <legend>基本信息</legend>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">商品名称</label>
                                    <div class="col-sm-4">
                                        <div class="form-inline">
                                            <input style="width: 70%;" type="text" name="name" required="" ng-model="NormalSaleProduct.Name" class="form-control" maxlength="200" />
                                        </div>
                                        <span ng-show="validateInput('name', 'required')" class="text-danger">请输入商品名称</span>
                                    </div>
                                    <div class="col-sm-4">
                                        <h4 class="text-danger">*</h4>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">商品描述</label>
                                    <div class="col-sm-4">
                                        <textarea rows="4" ng-model="NormalSaleProduct.Description" class="form-control" maxlength="500"></textarea>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">编码</label>
                                    <div class="col-sm-3">
                                        <input class="form-control" maxlength="50" ng-model="NormalSaleProduct.BarCode" type="text">
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">库存</label>
                                    <div class="col-sm-2">
                                        <input class="form-control" required="" name="stock" maxlength="20" ng-model="NormalSaleProduct.Stock" type="number" ng-pattern="/^\d+$/">
                                        <span ng-show="validateInput('stock', 'required')" class="text-danger">请输入商品库存</span>
                                        <span ng-show="validateInput('stock', 'pattern')" class="text-danger">请输入正确的库存</span>
                                    </div>
                                    <div class="col-sm-4">
                                        <h4 class="text-danger">*</h4>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">市场价</label>
                                    <div class="col-sm-2">
                                        <input class="form-control" required="" name="marketPrice" maxlength="10" ng-model="NormalSaleProduct.MarketPrice" type="number" ng-pattern="/^(([0-9]|([1-9][0-9]{0,9}))((\.[0-9]{1,2})?))$/">
                                        <span ng-show="validateInput('marketPrice', 'required')" class="text-danger">请输入商品市场价</span>
                                        <span ng-show="validateInput('marketPrice', 'pattern')" class="text-danger">请输入正确的市场价</span>
                                    </div>
                                    <div class="col-sm-4">
                                        <h4 class="text-danger">*</h4>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">积分</label>
                                    <div class="col-sm-2">
                                        <input class="form-control" required="" name="points" maxlength="20" ng-model="NormalSaleProduct.Points" type="number" ng-pattern="/^\d+$/">
                                        <span ng-show="validateInput('points', 'required')" class="text-danger">请输入商品积分</span>
                                        <span ng-show="validateInput('points', 'pattern')" class="text-danger">请输入正确的积分</span>
                                    </div>
                                    <div class="col-sm-4">
                                        <h4 class="text-danger">*</h4>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">兑换等级</label>
                                    <div class="col-sm-2">
                                        <div class="form-inline">
                                            <select ng-options="m.Id as m.LevelName for m in MemberLevelList" ng-model="NormalSaleProduct.ExchangeLevel" class="form-control">
                                                <option value="">请选择兑换等级</option>
                                            </select>及以上
                                        </div>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">排序</label>
                                    <div class="col-sm-1">
                                        <input class="form-control" maxlength="8" ng-model="NormalSaleProduct.Sort" type="number">
                                    </div>
                                    <div class="col-sm-6">
                                        <div class="text-danger form-control-static">数字越大显示在前台列表最前面，不填默认排序0，排序相同按照时间倒序</div>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">商品主图</label>
                                    <div class="col-sm-2">
                                        <div class="imgcrop-preview">
                                            <img ng-src="{{myCroppedImage}}" style="max-width: 100%; max-height: 100%" onerror="javascript: this.src = '/Content/img/default.png';" />
                                            <input id="fileInput" class="ng-hide" type="file" nv-file-select="" uploader="uploader" />
                                        </div>
                                        <div>
                                            <div style="" class="progress progress-xs" ng-show="uploading">
                                                <div role="progressbar" ng-style="{ 'width': uploader.progress + '%' }" class="progress-bar"></div>
                                            </div>
                                        </div>
                                        <span ng-show="IsCheckedPic" class="text-danger">请选择商品主图</span>
                                    </div>
                                    <div class="col-sm-4">
                                        <button type="button" class="mb-sm btn btn-info" id="selectImage">
                                            图片选择
                                        </button>
                                        <span class="text-danger">建议尺寸：640x640</span>
                                    </div>
                                    <div class="col-sm-2">
                                        <h4 class="text-danger">*</h4>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">商品附属图</label>
                                    <div class="col-sm-1" ng-repeat="imgUrl in NormalSaleProduct.SubImgUrls track by $index">
                                        <img src="/Content/img/pro_detail_03.png"
                                             style="position: absolute; width: 23px; height: 23px; right: 5px; top: -6px;"
                                             ng-click="croppedImageList.splice($index,1);NormalSaleProduct.SubImgUrls.splice($index,1)">
                                        <img ng-src="{{ImgHostUrl + imgUrl}}" style="max-width: 100%; max-height: 100%" onerror="javascript: this.src =  '/Content/img/default.png';" />
                                    </div>
                                    <div class="col-sm-2">
                                        <input type="hidden" id="uploadFlag" />
                                        <button type="button" class="mb-sm btn btn-info" id="selectImageSub" ng-show="croppedImageList.length<5">
                                            添加图片
                                        </button>
                                    </div>
                                    <div class="col-sm-4">
                                        <span class="text-danger">建议尺寸：320x320,最多5张</span>
                                    </div>
                                </div>
                            </fieldset>
                        </div>
                    </div>
                    <!-- END panel-->
                    <!--详情-->
                    <div class="panel panel-default" ng-class="{ 'whirl standard': isLoading}">
                        <div class="panel-body">
                            <fieldset class="b0">
                                <legend>商品详情</legend>
                            </fieldset>
                            <fieldset>
                                <div class="col-sm-1"></div>
                                <div class="col-sm-10">
                                    @*<summernote height="400" ng-model="NormalSaleProduct.Detail" on-image-upload="summernoteImgUpload(files)"></summernote>*@
                                    @*<ng-quill-editor ng-model="NormalSaleProduct.Detail" required="true" modules="{toolbar: false}"></ng-quill-editor>*@
                                    <script type="text/plain" id="Detail" name="Detail" style="height: 400px; width:90%" ng-bind="NormalSaleProduct.Detail" >
                                    </script>
                                </div>
                            </fieldset>
                        </div>
                    </div>
                    <div class="text-right">
                        <button type="button" class="btn btn-warning" ng-click="cancel()">返回列表</button>
                        <button type="button" class="btn btn-info" ng-click="saveNormalProduct()">保 存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    App.controller('ExchangeEditController', ["$scope", "$state", "$http", "$stateParams", "Notify", "FileUploader", 'ngTableParams', 'ngTableDataService', 'ngDialog', '$filter', '$rootScope',
        function ($scope, $state, $http, $stateParams, Notify, FileUploader, ngTableParams, ngTableDataService, ngDialog, $filter, $rootScope) {
            'use strict';
            $scope.submitted = false;
            $scope.isLoading = true;
            $scope.IsCheckedPic = false;
            $scope.croppedImageList = [];
            $scope.validateInput = function (name, type) {
                var input = $scope.formValidate[name];
                return (input.$dirty || $scope.submitted) && input.$error[type];
            };


            var um;
            var tt = function () {
                um == UM.getEditor('Detail');
            }

            setTimeout(tt, 1000);

            //数据初始化
            $http.post("/ProductExchange/ExchangeEdit", { Id: $stateParams.Id }).then(function (response) {
                $scope.NormalSaleProduct = response.data;
                if (!$scope.NormalSaleProduct) {
                    $scope.NormalSaleProduct = {
                        SubImgUrls: []
                    };
                } else {
                    $scope.myCroppedImage = $rootScope.ImgHostUrl + angular.copy($scope.NormalSaleProduct.ImgUrl);
                    if ($scope.NormalSaleProduct.SubImgUrls) {
                        angular.forEach($scope.NormalSaleProduct.SubImgUrls, function (value, index) {
                            $scope.croppedImageList.push($rootScope.ImgHostUrl + value);
                        });
                    }
                }

                $scope.isLoading = false;
            });

            $http.post("/ProductExchange/GetMemberLevels").then(function (response) {
                $scope.MemberLevelList = response.data;
            });

            // 提交
            $scope.saveNormalProduct = function () {
                $scope.submitted = true;
                $scope.isLoading = true;
                if ($scope.formValidate.$valid) {
                    if (!$scope.NormalSaleProduct.ImgUrl || $scope.NormalSaleProduct.ImgUrl == "") {
                        $scope.IsCheckedPic = true;
                        $scope.isLoading = false;
                        Notify.alert("请选择产品主图", { status: 'warning' });
                        return false;
                    }
                    if (!$scope.NormalSaleProduct.ExchangeLevel || $scope.NormalSaleProduct.ExchangeLevel == 0) {
                        $scope.isLoading = false;
                        Notify.alert("请选择兑换等级", { status: 'warning' });
                        return false;
                    }

                    if (!$scope.NormalSaleProduct.Points>0) {
                        $scope.isLoading = false;
                        Notify.alert("积分必须大于0", { status: 'warning' });
                        return false;
                    }
                    $scope.NormalSaleProduct.Detail = UM.getEditor('Detail').getContent();
                    $http.post("/ProductExchange/ExchangeEditSubmit", { ExchangeModel: $scope.NormalSaleProduct }).then(function (returnData) {
                        if (returnData.data.isSuccess) {
                            Notify.alert('操作成功!', { status: 'success', timeout: 1000 });

                            $state.go('app.exchangeManage', $stateParams);
                        } else {
                            Notify.alert(returnData.data.msg, { status: 'warning', timeout: 1000 });
                        }
                        $scope.isLoading = false;
                    });
                } else {
                    $scope.isLoading = false;
                    Notify.alert("请将信息填写完整后提交", { status: 'warning' });
                    var scrollTop = 0;
                    var index = 0;
                    for (var name in $scope.formValidate.$error) {
                        if ($scope.formValidate.$error.hasOwnProperty(name)) {
                            if (index === 0) {
                                scrollTop = $("[name=" + $scope.formValidate.$error[name][0].$name + "]").offset().top - 100;
                            }
                            if ($("[name=" + $scope.formValidate.$error[name][0].$name + "]").offset().top - 100 < scrollTop) {
                                scrollTop = $("[name=" + $scope.formValidate.$error[name][0].$name + "]").offset().top - 100;
                            }
                            index++;
                        }
                    }
                    document.body.scrollTop = scrollTop;
                    return false;
                }
            };

            //返回列表
            $scope.cancel = function () {
                $state.go("app.exchangeManage", $stateParams);
            }


            //-------------图片选择相关
            //主图
            $("#selectImage").click(function () {
                $("#uploadFlag").val(0);
                $("#fileInput").click();
            });
            //附属图
            $("#selectImageSub").click(function () {
                $("#uploadFlag").val(1);
                $("#fileInput").click();
            });

            var handleFileSelect = function (evt) {
                var file = $scope.uploadSelectFile = evt.currentTarget.files[0];
                if (!evt.currentTarget.files[0] || ! /image\/\w+/.test(evt.currentTarget.files[0].type)) {
                    Notify.alert('请选择图像文件', { status: 'warning' });
                    return false;
                }
                if (file.size > 1 * 1024 * 1024) {
                    Notify.alert('图片大小不能大于1MB', { status: 'warning', timeout: 3000 });
                    $scope.uploadSelectFile = null;
                    return false;
                }
                var reader = new FileReader();
                reader.onload = function (evt) {
                    $scope.$apply(function ($scope) {
                        if ($("#uploadFlag").val() == 1 && $scope.croppedImageList.length < 5) {
                            $scope.croppedImageList.push(evt.target.result);
                        } else if ($("#uploadFlag").val() == 0) {
                            $scope.myCroppedImage = evt.target.result;
                        }
                    });
                };
                if (file)
                    reader.readAsDataURL(file);
            };

            angular.element(document.querySelector('#fileInput')).on('change', handleFileSelect);
            var uploader = $scope.uploader = new FileUploader({
                url: $rootScope.ImgUploadUrl + '?PlatForm=wsd&Path=ProductExchange&CutType=320'
            });
            uploader.filters.push({
                name: 'customFilter',
                fn: function (item /*{File|FileLikeObject}*/, options) {
                    return this.queue.length < 10;
                }
            });

            // CALLBACKS

            uploader.onWhenAddingFileFailed = function (item /*{File|FileLikeObject}*/, filter, options) {
                //  console.info('onWhenAddingFileFailed', item, filter, options);
            };
            uploader.onAfterAddingFile = function (fileItem) {

                if ($scope.uploadSelectFile && /image\/\w+/.test($scope.uploadSelectFile.type) && (($("#uploadFlag").val() == 1 && $scope.croppedImageList.length < 5) || $("#uploadFlag").val() != 1)) {
                    fileItem.upload();
                } if ($("#uploadFlag").val() == 0) {
                    $scope.uploading = true;
                }

                //    console.info('onAfterAddingFile', fileItem);
            };
            uploader.onAfterAddingAll = function (addedFileItems) {
                //   console.info('onAfterAddingAll', addedFileItems);
            };
            uploader.onBeforeUploadItem = function (item) {
                // console.info('onBeforeUploadItem', item);
            };
            uploader.onProgressItem = function (fileItem, progress) {
                // console.info('onProgressItem', fileItem, progress);
            };
            uploader.onProgressAll = function (progress) {
                //  console.info('onProgressAll', progress);
            };
            uploader.onSuccessItem = function (fileItem, response, status, headers) {
                if ($("#uploadFlag").val() == 1) {
                    if (!$scope.NormalSaleProduct.SubImgUrls) {
                        $scope.NormalSaleProduct.SubImgUrls = [];
                    }
                    $scope.NormalSaleProduct.SubImgUrls.push(response[0]);
                } else if ($("#uploadFlag").val() == 0) {
                    $scope.NormalSaleProduct.ImgUrl = response[0];
                }
                $("#fileInput").val("");
                //  console.info('onSuccessItem', fileItem, response, status, headers);
            };
            uploader.onErrorItem = function (fileItem, response, status, headers) {
                //  console.info('onErrorItem', fileItem, response, status, headers);
            };
            uploader.onCancelItem = function (fileItem, response, status, headers) {
                // console.info('onCancelItem', fileItem, response, status, headers);
            };
            uploader.onCompleteItem = function (fileItem, response, status, headers) {
                //  console.info('onCompleteItem', fileItem, response, status, headers);
            };
            uploader.onCompleteAll = function () {
                $scope.uploading = false;
            };

            //---------详情
            $scope.summernoteImgUpload = function sendFile(file) {
                var data = new FormData();
                data.append("file", file[0]);
                data.append("type", 0);
                data.append("FullUrl", true);
                $.ajax({
                    data: data,
                    type: "POST",
                    url: $rootScope.ImgUploadUrl + '?PlatForm=wsd&Path=ProductExchange',
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (response) {
                        $('.summernote').summernote('editor.insertImage', $rootScope.ImgHostUrl + response[0]);
                    }
                });
            }



            //// 日期插件
            //$scope.picker1 = {
            //    date: new Date()
            //};

            //$scope.datepickerOptions = {
            //    showWeeks: false,
            //    startingDay: 1,
            //    dateDisabled: function (data) {
            //        //return (data.mode === 'day' && (new Date().toDateString() == data.date.toDateString()));
            //    }
            //}

            //$scope.openCalendar = function (e, picker) {
            //    $scope[picker].open = true;
            //};


            


        }]);
</script>
